import java.util.*;

public class Main {
    public static void main(String[] args) {
         List<Integer> l1 = new ArrayList<>();
         l1.add(1);
         l1.add(2);
         l1.add(3);

        List<Integer> l2 = new ArrayList<>();
        l2.add(0);
        l2.add(0);
        l2.add(0);
        List<Integer> l3 = new ArrayList<>();
        l3.add(7);
        l3.add(6);
        l3.add(5);

        List<List<Integer>> add = new ArrayList<>();
        add.add(l1);
        add.add(l2);
        add.add(l3);
        Solution.cutOffTree(add);
    }
}
class Solution {
    int m;
    int n;
    public int cutOffTree(List<List<Integer>> forest) {

        m = forest.size();
        n = forest.get(0).size();
        //确定砍树的顺序, 存放坐标
        List<int[]> trees = new ArrayList<>();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(forest.get(i).get(j) > 1) trees.add(new int[]{i, j});
            }
        }
        Collections.sort(trees, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return forest.get(o1[0]).get(o1[1]) - forest.get(o2[0]).get(o2[1]);
            }
        });

        //按照顺序砍树
        int ret = 0;
        int beginX = 0, beginY = 0;
        for (int[] tree : trees) {
            int x = tree[0];
            int y = tree[1];
            int step = 0;
            step = bfs(forest, beginX, beginY, x, y);
            if(step == -1) return -1;
            ret += step;
            beginX = x;
            beginY = y;
        }
        return ret;
    }
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    private int bfs(List<List<Integer>> forest, int beginX, int beginY, int x, int y) {
        if(beginX == x && beginY == y) return 0;

        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{beginX, beginY});
        boolean[][] visited = new boolean[m][n];
        visited[beginX][beginY] = true;
        int step = 0;
        while(!queue.isEmpty()){
            int sz = queue.size();
            step++;
            for (int i = 0; i < sz; i++) {
                int[] poll = queue.poll();
                for(int k = 0; k < 4; k++){
                    int row = dx[k] + poll[0];
                    int col = dy[k] + poll[1];
                    if(row >= 0 && row < m && col >= 0 && col < n && forest.get(row).get(col) > 0
                            && !visited[row][col]){
                        if(x == row && y == col) return step;
                        queue.offer(new int[]{row, col});
                        visited[row][col] = true;
                    }
                }
            }
        }

        return -1;
    }
}